#include "mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent) {
    setWindowTitle("图像对比工具");
    resize(1200, 800);

    QWidget* central = new QWidget(this);
    QHBoxLayout* layout = new QHBoxLayout(central);

    leftLabel = new ImageLabel(this);
    rightLabel = new ImageLabel(this);

    layout->addWidget(leftLabel);
    layout->addWidget(rightLabel);

    connect(leftLabel, &ImageLabel::regionSelected, this, &MainWindow::handleRegionSelected);

    setCentralWidget(central);

    // 菜单栏
    QMenu* fileMenu = menuBar()->addMenu("文件");
    fileMenu->addAction("加载图1", this, &MainWindow::loadImage1);
    fileMenu->addAction("加载图2", this, &MainWindow::loadImage2);
    fileMenu->addAction("退出", this, &MainWindow::close);
}

MainWindow::~MainWindow() {}

void MainWindow::loadImage1() {
    QString file = QFileDialog::getOpenFileName(this, "选择图像1");
    if (file.isEmpty()) return;

    img1 = cv::imread(file.toStdString());
    if (!img1.empty())
        updateDisplay();
}

void MainWindow::loadImage2() {
    QString file = QFileDialog::getOpenFileName(this, "选择图像2");
    if (file.isEmpty() || img1.empty()) return;

    img2 = cv::imread(file.toStdString());
    registerImage();
    updateDisplay();
}

void MainWindow::registerImage() {
    cv::Mat gray1, gray2;
    cv::cvtColor(img1, gray1, cv::COLOR_BGR2GRAY);
    cv::cvtColor(img2, gray2, cv::COLOR_BGR2GRAY);

    auto sift = cv::SIFT::create();
    std::vector<cv::KeyPoint> kp1, kp2;
    cv::Mat des1, des2;

    sift->detectAndCompute(gray1, cv::noArray(), kp1, des1);
    sift->detectAndCompute(gray2, cv::noArray(), kp2, des2);

    cv::FlannBasedMatcher matcher;
    std::vector<std::vector<cv::DMatch>> knnMatches;
    matcher.knnMatch(des1, des2, knnMatches, 2);

    std::vector<cv::DMatch> goodMatches;
    for (const auto& m : knnMatches) {
        if (m[0].distance < 0.7 * m[1].distance)
            goodMatches.push_back(m[0]);
    }

    if (goodMatches.size() < 4) return;

    std::vector<cv::Point2f> pts1, pts2;
    for (auto& m : goodMatches) {
        pts1.push_back(kp1[m.queryIdx].pt);
        pts2.push_back(kp2[m.trainIdx].pt);
    }

    homography = cv::findHomography(pts2, pts1, cv::RANSAC);
    cv::warpPerspective(img2, img2_aligned, homography, img1.size());
}

void MainWindow::updateDisplay() {
    if (!img1.empty()) {
        QImage q1 = cvMatToQImage(img1);
        leftLabel->setPixmapWithScale(QPixmap::fromImage(q1), scale1);
    }
    if (!img2_aligned.empty()) {
        QImage q2 = cvMatToQImage(img2_aligned);
        rightLabel->setPixmapWithScale(QPixmap::fromImage(q2), scale2);
        rightLabel->update(); // 确保能刷新绘制后的图像

    }


}

void MainWindow::handleRegionSelected(QRect rect) {
    if (img1.empty() || img2_aligned.empty() || homography.empty())
        return;

    float x1 = rect.left() / scale1;
    float y1 = rect.top() / scale1;
    float x2 = rect.right() / scale1;
    float y2 = rect.bottom() / scale1;

    std::vector<cv::Point2f> srcPts = {
            cv::Point2f(x1, y1),
            cv::Point2f(x2, y1),
            cv::Point2f(x2, y2),
            cv::Point2f(x1, y2)
    };

    std::vector<cv::Point2f> dstPts;
    cv::perspectiveTransform(srcPts, dstPts, homography);

    // 获取右图原图副本
    QPixmap pixmap = *rightLabel->pixmap();  // 复制当前 pixmap
    QPainter painter(&pixmap);
    painter.setPen(QPen(Qt::blue, 2));

    QPolygon mappedPolygon;
    for (const auto& pt : dstPts) {
        QPoint qp(pt.x * scale2, pt.y * scale2);  // 缩放坐标
        mappedPolygon << qp;
    }

    painter.drawPolygon(mappedPolygon);
    painter.end();

    // 更新右图
    rightLabel->setPixmap(pixmap);
    rightLabel->update();
}



QImage MainWindow::cvMatToQImage(const cv::Mat& mat) {
    if (mat.channels() == 3)
        return QImage(mat.data, mat.cols, mat.rows, mat.step, QImage::Format_BGR888).copy();
    else
        return QImage(mat.data, mat.cols, mat.rows, mat.step, QImage::Format_Grayscale8).copy();
}
